import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import '../models/photo_album.dart';
import '../services/storage_service.dart';

class AlbumPage extends StatefulWidget {
  const AlbumPage({Key? key}) : super(key: key);

  @override
  _AlbumPageState createState() => _AlbumPageState();
}

class _AlbumPageState extends State<AlbumPage> with AutomaticKeepAliveClientMixin {
  final StorageService _storageService = StorageService();
  final ImagePicker _picker = ImagePicker();
  List<PhotoAlbum> _albums = [];
  bool _isLoading = true;

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();
    _loadAlbums();
  }

  Future<void> _loadAlbums() async {
    setState(() {
      _isLoading = true;
    });

    final albums = await _storageService.getPhotoAlbums();

    setState(() {
      _albums = albums;
      _isLoading = false;
    });
  }

  Future<void> _createNewAlbum() async {
    final TextEditingController nameController = TextEditingController();

    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('创建新相册'),
          content: TextField(
            controller: nameController,
            decoration: const InputDecoration(
              hintText: '相册名称',
              prefixIcon: Icon(Icons.photo_album),
            ),
            autofocus: true,
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                if (nameController.text.isNotEmpty) {
                  final newAlbum = PhotoAlbum(
                    id: DateTime.now().millisecondsSinceEpoch.toString(),
                    name: nameController.text,
                    coverImage: null,
                    photos: [],
                    createdAt: DateTime.now(),
                  );

                  await _storageService.addPhotoAlbum(newAlbum);
                  _loadAlbums();
                  Navigator.pop(context);

                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('相册 "${nameController.text}" 创建成功')),
                  );
                }
              },
              child: const Text('创建'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _deleteAlbum(String id, String name) async {
    // 显示确认对话框
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除相册"$name"吗？相册中的所有照片都将被删除，此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    // 如果用户确认删除
    if (confirm == true) {
      await _storageService.deletePhotoAlbum(id);
      _loadAlbums(); // 重新加载数据

      // 显示删除成功提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('相册"$name"已删除')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        title: const Text('私密相册'),
        elevation: 0,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            bottom: Radius.circular(16),
          ),
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
        onRefresh: _loadAlbums,
        child: _albums.isEmpty && !_isLoading
            ? Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.photo_library_outlined,
                size: 80,
                color: Colors.grey[400],
              ),
              const SizedBox(height: 16),
              Text(
                '还没有相册，点击下方按钮创建',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: _createNewAlbum,
                icon: const Icon(Icons.add),
                label: const Text('创建相册'),
              ),
            ],
          ),
        )
            : GridView.builder(
          padding: const EdgeInsets.all(16.0),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 16.0,
            mainAxisSpacing: 16.0,
            childAspectRatio: 0.8,
          ),
          itemCount: _albums.length + 1, // +1 for the "Create New Album" tile
          itemBuilder: (context, index) {
            if (index == 0) {
              // "Create New Album" tile
              return GestureDetector(
                onTap: _createNewAlbum,
                child: Card(
                  elevation: 2,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16.0),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          color: Theme.of(context).primaryColor.withOpacity(0.1),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.add_photo_alternate,
                          size: 30,
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                      const SizedBox(height: 16),
                      const Text(
                        '创建新相册',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }

            final album = _albums[index - 1];
            return Stack(
              children: [
                GestureDetector(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => AlbumDetailPage(album: album),
                      ),
                    ).then((_) => _loadAlbums());
                  },
                  child: Card(
                    elevation: 4,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16.0),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: const BorderRadius.vertical(top: Radius.circular(16.0)),
                              image: album.coverImage != null
                                  ? DecorationImage(
                                image: FileImage(album.coverImage!),
                                fit: BoxFit.cover,
                              )
                                  : null,
                              color: album.coverImage == null ? Colors.grey[200] : null,
                            ),
                            child: album.coverImage == null
                                ? Center(
                              child: Icon(
                                Icons.photo_library,
                                size: 40,
                                color: Colors.grey[400],
                              ),
                            )
                                : null,
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                album.name,
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '${album.photos.length}张照片',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Positioned(
                  top: 8,
                  right: 8,
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      borderRadius: BorderRadius.circular(20),
                      onTap: () => _deleteAlbum(album.id, album.name),
                      child: Container(
                        padding: const EdgeInsets.all(6),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.5),
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.delete_outline,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
      floatingActionButton: _isLoading
          ? null
          : FloatingActionButton(
        onPressed: _createNewAlbum,
        child: const Icon(Icons.add_photo_alternate),
        tooltip: '创建新相册',
      ),
    );
  }
}

class AlbumDetailPage extends StatefulWidget {
  final PhotoAlbum album;

  const AlbumDetailPage({Key? key, required this.album}) : super(key: key);

  @override
  _AlbumDetailPageState createState() => _AlbumDetailPageState();
}

class _AlbumDetailPageState extends State<AlbumDetailPage> {
  final StorageService _storageService = StorageService();
  final ImagePicker _picker = ImagePicker();
  late PhotoAlbum _album;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _album = widget.album;
  }

  Future<void> _addPhoto() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );

      if (image != null) {
        final File imageFile = File(image.path);

        setState(() {
          _album.photos.add(imageFile);
          if (_album.coverImage == null) {
            _album.coverImage = imageFile;
          }
        });

        await _storageService.updatePhotoAlbum(_album);

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('照片已添加')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('添加照片失败: $e')),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _deletePhoto(int index) async {
    // 显示确认对话框
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这张照片吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    // 如果用户确认删除
    if (confirm == true) {
      final deletedPhoto = _album.photos[index];

      setState(() {
        _album.photos.removeAt(index);

        // 如果删除的是封面图片，则更新封面
        if (_album.coverImage == deletedPhoto) {
          _album.coverImage = _album.photos.isNotEmpty ? _album.photos[0] : null;
        }
      });

      await _storageService.updatePhotoAlbum(_album);

      // 显示删除成功提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('照片已删除')),
      );
    }
  }

  Future<void> _setAsCover(int index) async {
    setState(() {
      _album.coverImage = _album.photos[index];
    });

    await _storageService.updatePhotoAlbum(_album);

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('已设为封面')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        title: Text(_album.name),
        elevation: 0,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            bottom: Radius.circular(16),
          ),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.edit),
            onPressed: () async {
              final TextEditingController nameController = TextEditingController(text: _album.name);

              final newName = await showDialog<String>(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('重命名相册'),
                  content: TextField(
                    controller: nameController,
                    decoration: const InputDecoration(
                      hintText: '相册名称',
                      prefixIcon: Icon(Icons.photo_album),
                    ),
                    autofocus: true,
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: const Text('取消'),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        if (nameController.text.isNotEmpty) {
                          Navigator.pop(context, nameController.text);
                        }
                      },
                      child: const Text('保存'),
                    ),
                  ],
                ),
              );

              if (newName != null && newName.isNotEmpty) {
                setState(() {
                  _album.name = newName;
                });

                await _storageService.updatePhotoAlbum(_album);

                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('相册已重命名为"$newName"')),
                );
              }
            },
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _album.photos.isEmpty
          ? Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.photo_library_outlined,
              size: 80,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '相册为空，点击右下角添加照片',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: _addPhoto,
              icon: const Icon(Icons.add_photo_alternate),
              label: const Text('添加照片'),
            ),
          ],
        ),
      )
          : GridView.builder(
        padding: const EdgeInsets.all(8.0),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 8.0,
          mainAxisSpacing: 8.0,
        ),
        itemCount: _album.photos.length,
        itemBuilder: (context, index) {
          return Stack(
            children: [
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PhotoViewPage(
                        photos: _album.photos,
                        initialIndex: index,
                      ),
                    ),
                  );
                },
                child: Hero(
                  tag: 'photo_${_album.id}_$index',
                  child: Card(
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    clipBehavior: Clip.antiAlias,
                    child: Image.file(
                      _album.photos[index],
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity,
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 4,
                right: 4,
                child: Material(
                  color: Colors.transparent,
                  child: PopupMenuButton<String>(
                    icon: Container(
                      padding: const EdgeInsets.all(4),
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.5),
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.more_vert,
                        color: Colors.white,
                        size: 16,
                      ),
                    ),
                    onSelected: (value) {
                      if (value == 'delete') {
                        _deletePhoto(index);
                      } else if (value == 'cover') {
                        _setAsCover(index);
                      }
                    },
                    itemBuilder: (context) => [
                       PopupMenuItem(
                        value: 'cover',
                        child: Row(
                          children: [
                            Icon(Icons.image, size: 18),
                            SizedBox(width: 8),
                            Text('设为封面'),
                          ],
                        ),
                      ),
                       PopupMenuItem(
                        value: 'delete',
                        child: Row(
                          children: [
                            Icon(Icons.delete, size: 18),
                            SizedBox(width: 8),
                            Text('删除'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              if (_album.coverImage == _album.photos[index])
                Positioned(
                  bottom: 4,
                  left: 4,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: const Text(
                      '封面',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
            ],
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addPhoto,
        child: const Icon(Icons.add_a_photo),
        tooltip: '添加照片',
      ),
    );
  }
}

class PhotoViewPage extends StatefulWidget {
  final List<File> photos;
  final int initialIndex;

  const PhotoViewPage({
    Key? key,
    required this.photos,
    required this.initialIndex,
  }) : super(key: key);

  @override
  _PhotoViewPageState createState() => _PhotoViewPageState();
}

class _PhotoViewPageState extends State<PhotoViewPage> {
  late PageController _pageController;
  late int _currentIndex;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: _currentIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(
          '${_currentIndex + 1}/${widget.photos.length}',
          style: const TextStyle(color: Colors.white),
        ),
      ),
      body: PageView.builder(
        controller: _pageController,
        itemCount: widget.photos.length,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        itemBuilder: (context, index) {
          return InteractiveViewer(
            minScale: 0.5,
            maxScale: 3.0,
            child: Center(
              child: Hero(
                tag: 'photo_${index}',
                child: Image.file(
                  widget.photos[index],
                  fit: BoxFit.contain,
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

